package com.itshizhan.itjidancideveloper.controller.ucenter;

import com.itshizhan.itjidancideveloper.dao.ArticleCategoryDao;
import com.itshizhan.itjidancideveloper.dao.ArticleDao;
import com.itshizhan.itjidancideveloper.models.Article;
import com.itshizhan.itjidancideveloper.models.ArticleCategory;
import com.itshizhan.itjidancideveloper.models.vo.ArticleQuery;
import com.itshizhan.itjidancideveloper.response.Response;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;

@RestController()
@RequestMapping("/ucenter/article")
public class ArticleController {

	@Autowired
	ArticleDao articleDao;
	@Autowired
	ArticleCategoryDao articleCategoryDao;
	@PostMapping("/list")
	public  Response<Page<Article>> getList(@RequestParam("pageIndex") Integer pageIndex,
																					@RequestParam("pageSize") Integer pageSize,
																					@RequestBody() ArticleQuery articleQuery
	) {
		//注意：从第0页开始的
		PageRequest pageable = PageRequest.of(pageIndex - 1, pageSize);
		Specification<Article> spec  = (Specification<Article>) (root, query, cBuilder) -> {
			/**模糊查询**/
			Predicate likeCondition = cBuilder.like(root.get("title"), "%" + articleQuery.getTitle() + "%");
			Predicate stateCondition = cBuilder.equal(root.get("state"), articleQuery.getState());
			query.where(likeCondition, stateCondition);
			return null;
		};
		Page<Article> pageArticle = articleDao.findAll(spec, pageable);
		return Response.success(pageArticle);
	}

	@GetMapping("/detail")
	Response<Article> getDetailById(@RequestParam("id") Integer id){
		Article article = articleDao.findById(id).orElse(null);
		return Response.success(article);
	}

	@PostMapping("/save")
	Response<Article> save(@RequestBody() Article article, @RequestParam("categoryId") Integer categoryId)  {
		Integer articleId = article.getId();
		if(articleId==0){
			//新增
			Article articleDb = articleDao.save(article);
			return Response.success(articleDb);
		}else {
			//修改
			System.out.println("修改---");
			System.out.println(article);
			Article dbArticle = articleDao.findById(articleId).orElse(null);
			if (dbArticle!=null) {
				dbArticle.setTitle(article.getTitle());
				dbArticle.setContentMd(article.getContentMd());
				dbArticle.setContentHtml(article.getContentHtml());
				ArticleCategory dbArticleCategory = articleCategoryDao.findById(categoryId).orElse(null);
				if(dbArticleCategory!=null){
					dbArticleCategory.setId(categoryId);
					dbArticle.setArticleCategory(dbArticleCategory);
					val saveArticle = articleDao.save(dbArticle);
					return Response.success(saveArticle);
				}else {
					return Response.fail("参数错误，当前分类不存在");
				}
			}else {
				return Response.fail();
			}
		}
	}
}
